/*
 * 快捷键：Ctrl + Enter 提交回答
 */

(function () {
  const {
    name,
  } = chrome.runtime.getManifest();

  const log = (...args) => {
    console.log.apply(console, [`${name}:`].concat(args));
  };

  var Confs = {
    first: { // 初次回答
      iframe: '#edui1_iframeholder iframe',
      submitBtn: '.new-editor-deliver-btn'
    },

    modify: { // `补充问题`、追问补打/ 我有更好的答案 动态插入的编辑框
      iframe: '#ueditor_0',
      submitBtn: '.addons.line > .new-editor-deliver-btn'
    },

    homepage: {
      iframe: '#ueditor_1',
      submitBtn: '.new-editor-deliver-btn',
    },
  };

  // 点击触发展开编辑器的按键们
  var Buttons = [
    "#answer-bar", // `我有更好的答案` 2016年9月8日
    '[alog-action="qb-modify-ans"]', // `完善我的回答`
    '.asker-btn.goon-ask', // `继续追问`
    '#wgt-myanswer .modify-answer-text', // `修改回答`
  ];

  function addSubmitEvent(editor, submitBtn) {
    editor.addEventListener('keydown', function (e) {
      var keyCode = e.keyCode;
      if (((e.ctrlKey || e.metaKey) && keyCode == 13) || // Ctrl + Enter | Command + Enter
        (e.altKey && keyCode == 67) // Alt + c
      ) {
        submitBtn.click();
      }
    });
  }

  function setup(conf) {
    var iframe = document.querySelector(conf.iframe);
    if (iframe) {
      var submitBtn = document.querySelector(conf.submitBtn); // 回答提交按钮
      if (submitBtn) {
        var editor = iframe.contentWindow.document.body;
        addSubmitEvent(editor, submitBtn);
      } else {
        console.log(`未找到提交按钮: ${conf.submitBtn}`);
      }
    } else {
      console.log(`未找到 iframe: ${conf.iframe}`);
    }
  }

  setTimeout(function () {
    setup(Confs.first);

    Buttons.forEach(function (button) {
      var modifyBtns = document.querySelectorAll(button);
      modifyBtns.forEach(function (btn) {
        if (btn) { // 点击时触发事件绑定
          btn.addEventListener('click', function () {
            setTimeout(function () {
              setup(Confs.modify);
            }, 1e3);
          });
        } else {
          log('未找到 触发展开编辑器的按键', button);
        }
      })
    })
  }, 1e3);

  // 签到
  const $ = (selector, doc = document) => {
    const dom = doc.querySelector(selector);
    if (!dom) {
      log('未找到节点:', selector);
    }
    return dom;
  };

  const GO_SIGN_IN = '.go-sign-in';
  const SIGN_IN_BTN = '#sign-in-btn';
  const CLOSE_LAYER = '.close-layer';
  const SIGN_IN_DIALOG = '.sign-in-dialog';
  const BOX_CAN_OPEN = '.box-can-open';

  // 打开签到面板里的宝箱
  function openBox(cb, delay) {
    var $box = $(BOX_CAN_OPEN);
    if ($box) {
      $box.click();
      setTimeout(function () {
        cb && cb();
      }, delay || 2e3); // delay 等待弹窗消失
    } else {
      cb && cb();
    }
  }

  function sign() {
    var $sign = $(GO_SIGN_IN);
    if ($sign) {
      var txt = $sign.textContent.trim();
      if (txt != '已签到') {
        $sign.click(); // 触发弹窗

        setTimeout(function () {
          var signBtn = $(SIGN_IN_BTN);
          if (signBtn) {
            signBtn.click();
          }

          openBox(function () {
            log('已自动签到。');
            var cont = $(SIGN_IN_DIALOG);
            if (cont) {
              var closeBtn = $(CLOSE_LAYER, cont);
              if (closeBtn) {
                closeBtn.click();
              }
            }
          });
        }, 500);
      } else {
        log('已签过到。');
      }
    } else {
      log('未找到签到入口。');
    }
  }

  const setBreadth = (status) => {
    $('body').classList.toggle('breadth_screen_crx', status);
  };

  setTimeout(sign, 1e3);

  /* 	setTimeout(function(){
      // 去除`为您推荐`
      document.querySelector('.wgt-bottom-union.mod-shadow.line').style.display = 'none';
      // 去除所有 iframe
      var iframes = document.querySelectorAll('iframe[src^="https://pos.baidu.com/"]');
      Array.prototype.forEach.call( iframes, function( ifr ){
        ifr.style.display = 'none';
      })
    }, 3e3) */
  chrome.extension.sendRequest({
    action: "getIsOpen"
  }, function (response) {
    const {
      isOpen
    } = response;
    setBreadth(isOpen);
  });

  chrome.runtime.onMessage.addListener((request, sender, response) => {
    const {
      action,
    } = request;

    switch (action) {
      case 'change-breadth': {
        const {
          isOpen,
        } = request;

        setBreadth(isOpen);
      }
      break;

    default:
      break;
    }
  });
})();

(() => {
  /**
   * 放大百度知道中点开的预览图 v3
   * g8up
   * 2020年4月4日
   */
  const getTransformVal = (el, prop) => {
    return el.dataset[prop];
  };

  const getRotateZ = el => (getTransformVal(el, 'rotateZ') || 0);

  const getScale = el => (getTransformVal(el, 'scale') || 1);

  const setTransform = (el, props) => {
    const {
      rotateZ = getRotateZ(el), scale = getScale(el),
    } = props;
    el.style.transform = `scale(${scale}) rotateZ(${rotateZ}deg)`;
    Object.assign(el.dataset, {
      rotateZ,
      scale,
    });
  };

  const initStyle = (el) => {
    el.style.transition = 'transform 0.2s ease 0s';
  };

  const mutationObserver = new MutationObserver((mutationsList) => {
    mutationsList.forEach(mutation => {
      if (mutation.attributeName === 'class'
        && document.body.classList.contains('q-img-body-noscroll')
      ) {
        const img = document.querySelector("body > div.q-img-fullscreen-wraper > img");

        if (img) {
          initStyle(img);
          let init = +getScale(img);
          const STEP = 0.1;
          let timer = null;

          img.onmousewheel = (e) => {
            e.preventDefault();
            const isDown = e.wheelDelta < 0;
            const range = isDown ? init -= STEP : init += STEP;
            clearTimeout(timer);
            timer = setTimeout((range) => {
              clearTimeout(timer);
              setTransform(img, {
                scale: range,
              });
            }, 200, range);
          }
        } else {
          console.warn(`未找到点开的缩略图。`);
        }
      }
    });
  });

  mutationObserver.observe(document.body, {
    attributes: true
  });
})();